package com.gitee.cashzhang27.test.cloud.oauth.auth.server.jdbc.configuration;

import com.gitee.cashzhang27.test.cloud.oauth.auth.server.jdbc.service.AuthUserDetailsService;
import javax.sql.DataSource;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

/**
 * 认证服务器配置
 *
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/01/26 11:32
 */
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

  /**
   * 自定义UserDetailsService
   */
  private final AuthUserDetailsService authUserDetailsService;
  /**
   * 认证管理器
   */
  private final AuthenticationManager authenticationManager;

  private PasswordEncoder passwordEncoder;

  private DataSource dataSource;

  /**
   * 用来配置客户端详情服务（ClientDetailsService）， 客户端详情信息在这里进行初始化， 你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息。
   */
  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.jdbc(dataSource);
  }

  /**
   * 用来配置令牌端点(Token Endpoint)的安全约束.
   */
  @Override
  public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
    oauthServer
        .tokenKeyAccess("permitAll()")
        .checkTokenAccess("permitAll()")
        .allowFormAuthenticationForClients();
  }

  /**
   * 用来配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)。
   */
  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    endpoints
        .authenticationManager(authenticationManager)
        .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
        .tokenStore(tokenStore())
        .userDetailsService(authUserDetailsService)
        .reuseRefreshTokens(false);
  }

  @Bean
  public TokenStore tokenStore() {
    return new JdbcTokenStore(dataSource);
  }

}
